<?php
declare (strict_types = 1);

namespace app\product\controller;

use app\product\BaseController;
use app\auth\common\util\ApiUtil;
use app\product\service\SupplierService;

class SupplierController extends BaseController
{
    public function __construct(SupplierService $supplierService)
    {
        $this->supplierService = $supplierService;
    }

    public function list(){
        $params = request()->param();
        $where = $limit = array();
        $limit['page'] = !empty($params['page'])?intval($params['page']):1;
        $limit['pagesize'] = !empty($params['pagesize'])?intval($params['pagesize']):10;
        $name = !empty($params['name'])?trim($params['name']):'';
        $url = !empty($params['url'])?trim($params['url']):'';
        $province_code = !empty($params['province_code'])?intval($params['province_code']):0;
        $city_code = !empty($params['city_code'])?intval($params['city_code']):0;
        $area_code = !empty($params['area_code'])?intval($params['area_code']):0;
        if(!empty($name)) $where[] = ['name', 'like', '%'.$name.'%' ];
        if(!empty($url)) $where[] = ['url', 'like', '%'.$url.'%' ];
        if(!empty($province_code)) $where[] = ['province_code','=', $province_code ];
        if(!empty($city_code)) $where[] = ['city_code', '=',$city_code ];
        if(!empty($area_code)) $where[] = ['area_code', '=',$area_code ];
        $total = $this->supplierService->count($where);
        $list = $this->supplierService->list($where , $limit);
        return ApiUtil::normal(['total'=>$total,'list'=>$list]);
    }

    public function add(){
        $params = request()->param();
        $data = $this->supplierService->verify($params);
        if(is_string($data)) return ApiUtil::normal(null, $data, ApiUtil::CODE_FAIL);
        $lastId = $this->supplierService->insertGetId($data);
        if(!$lastId) return ApiUtil::normal('', '添加失败',ApiUtil::CODE_SERVER_ERROR);
        return ApiUtil::normal( ['id'=>$lastId]);
    }

    public function edit(){
        $params = request()->param();
        $id = input('id',0);
        if(empty($id)) return ApiUtil::normal('', 'ID不能为空',ApiUtil::CODE_FAIL);
        $data = $this->supplierService->verify($params,intval($id));
        if(is_string($data)) return ApiUtil::normal(null, $data, ApiUtil::CODE_FAIL);
        $update = $this->supplierService->update(['id'=>$id],$data);
        if(!$update) return ApiUtil::normal('', '编辑失败',ApiUtil::CODE_SERVER_ERROR);
        return ApiUtil::normal(['id'=>$id]);
    }

    public function delete(){
        $ids = input('id',[]);
        if(empty($ids) || !is_array($ids)) return ApiUtil::normal(null, '参数必须是数组，且不能为空', ApiUtil::CODE_FAIL);
        $del = $this->supplierService->delete(['id',$ids]);
        if(!$del) return ApiUtil::normal('', '删除失败',ApiUtil::CODE_SERVER_ERROR);
        return ApiUtil::normal(['id'=>$ids]);
    }
}
